package com.fc.converters;

import javax.faces.bean.ApplicationScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.fc.entities.FoodGroup;
import com.fc.service.FoodGroupService;
import com.fc.utils.ServiceLocator;

/**
 * 
 * @author aacs
 * 
 */
@Component("foodGroupConverter")
@ApplicationScoped
public class FoodGroupConverter implements Converter{
	private FoodGroupService service;

	public FoodGroupService getService() {
		if (service == null) {
			service = ServiceLocator.getBean(FoodGroupService.class);	
		}
		return service;
	}
	
	
	@Override
	public FoodGroup getAsObject(FacesContext context, UIComponent component, String value) {
		if (StringUtils.isBlank(value)) {
			return null;
		}

		return getService().findByName(value);
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		if (value == null || !(value instanceof FoodGroup)) {
			return "";
		}
		FoodGroup foodGroup = (FoodGroup) value;
		return String.valueOf(foodGroup.getName());
	}
}
